#include "../../serve.hpp"
#include <fstream>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <regex>
#include <string>
std::unordered_map<std::string, std::string> _cotains = {
    {".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"},
};
std::unordered_map<int, std::string> _status = {
    {100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"},

};

class Util
{
public:
    // 字符串分割函数,将src字符串按照sep字符进行分割，得到的各个字串放到arry中，最终返回字串的数量
    static size_t Split(const std::string &src, const std::string &sep, std::vector<std::string> *arry)
    {
        size_t begin = 0;
        while (begin < src.size())
        {
            size_t pos = src.find(sep, begin);
            // 没有找到
            if (pos == std::string::npos)
            {
                if (src.size() - begin > 0)
                {
                    arry->push_back(src.substr(begin));
                }
                return arry->size();
            }
            // 找到了进行判断
            if (pos - begin > 0)
            {
                arry->push_back(src.substr(begin, pos - begin));
            }
            begin = pos + sep.size();
        }
        return arry->size();
    }
    /*

        czy@iv-ydymv3isjkcva4g3znj3:~/linux-learning/project/ReactorServ/source/http$ md5sum test.txt
        1e8f251b335451df4ec4e911aaba5325  test.txt
        czy@iv-ydymv3isjkcva4g3znj3:~/linux-learning/project/ReactorServ/source/http$ md5sum Makefile
        1e8f251b335451df4ec4e911aaba5325  Makefile
    */
    // 读取文件的所有内容，将读取的内容放到一个buf中
    static bool ReadFile(const std::string &filename, std::string *buf)
    {
        std::ifstream in(filename.c_str(), std::ios::binary);
        if (in.is_open() == false)
        {
            ERR_LOG("OPEN %s FILE ERROR", filename.c_str());
            in.close();
            return false;
        }
        int length = 0;
        in.seekg(0, std::ios::end);
        length = in.tellg();
        in.seekg(0, std::ios::beg);
        buf->resize(length);
        in.read((&(*buf)[0]), length);
        if (in.good() == false)
        {
            ERR_LOG("READ %s ERROR", filename.c_str());
            in.close();
        }
        in.close();
        return true;
    }
    // 向文件写入数据 打开文件不存在会进行创建
    static bool WriteFile(const std::string &filename, const std::string &buf)
    {
        std::ofstream out(filename.c_str(), std::ios::binary | std::ios::trunc);
        if (out.is_open() == false)
        {
            DBG_LOG("OPEN %s FILE ERROR", filename.c_str());
            out.close();
            return false;
        }
        out.write(buf.c_str(), buf.size());
        if (out.good() == false)
        {
            ERR_LOG("WRITE %s ERROR", filename.c_str());
            out.close();
        }
        out.close();
        return true;
    }
    // URL编码，避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中特殊字符产生歧义
    // 编码格式：将特殊字符的ascii值，转换为两个16进制字符，前缀%   C++ -> C%2B%2B
    //   不编码的特殊字符： RFC3986文档规定 . - _ ~ 字母，数字属于绝对不编码字符
    // RFC3986文档规定，编码格式 %HH
    // W3C标准中规定，查询字符串中的空格，需要编码为+， 解码则是+转空格
    // isalnum() checks for an alphanumeric character; it is equivalent to (isalpha(c) || isdigit(c)).
    static std::string UrlEncode(const std::string url, bool convert_space_to_plus)
    {
        std::string ret;
        for (auto &ch : url)
        {
            // 另外数字和大小写字母也不进行编码
            if (ch == '.' || ch == '-' || ch == '_' || ch == '~' || isalnum(ch))
            {
                ret += ch;
                continue;
            }
            if (ch == ' ' && convert_space_to_plus)
            {
                ret += '+';
                continue;
            }

            // 其他字符就是特殊字符进行编码
            char temp[4];
            snprintf(temp, 4, "%%%02X", ch);
            ret += temp;
        }
        return ret;
    }

    static char HEXTOI(char c)
    {
        if (islower(c))
        {
            return c - 'a' + 10;
        }
        if (isupper(c))
        {
            return c - 'A' + 10;
        }
        return c - '0';
    }
    static std::string UrlDecode(const std::string url, bool convert_plus_to_space)
    {
        std::string ret;
        for (int i = 0; i < url.size(); i++)
        {
            if (url[i] == '+' && convert_plus_to_space)
            {
                ret += ' ';
                continue;
            }
            if (url[i] == '%')
            {
                char tem1 = HEXTOI(url[i + 1]);
                char tem2 = HEXTOI(url[i + 2]);
                ret += tem1 * 16 + tem2;
                i += 2;
                continue;
            }
            ret += url[i];
        }
        return ret;
    }
    // 响应状态码的描述信息获取
    static std::string StatuDesc(int statu)
    {

        auto it = _status.find(statu);
        if (it == _status.end())
        {
            return "NoFound";
        }
        return it->second;
    }
    // 根据文件后缀名获取文件mime
    static std::string ExtMime(const std::string &filename)
    {

        // 先要提取文件的后缀
        size_t pos = filename.rfind('.');
        if (pos == std::string::npos)
        {
            return "application/octet-stream";
        }
        std::string tem = filename.substr(pos);
        auto it = _cotains.find(tem);
        if (it == _cotains.end())
        {
            return "application/octet-stream";
        }
        return it->second;
    }
    // 判断一个文件是否是一个目录
    // st_mode This field contains the file type and mode.  See inode(7) for further information.
    static bool IsDirectory(const std::string &filename)
    {
        struct stat st;
        // stat 获取文件属性

        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }
        return S_ISDIR(st.st_mode);
    }
    // 判断一个文件是否是一个普通文件
    static bool IsRegular(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }
        return S_ISREG(st.st_mode);
    }
    // http请求的资源路径有效性判断
    //  /index.html  --- 前边的/叫做相对根目录  映射的是某个服务器上的子目录
    //  想表达的意思就是，客户端只能请求相对根目录中的资源，其他地方的资源都不予理会
    //  /../login, 这个路径中的..会让路径的查找跑到相对根目录之外，这是不合理的，不安全的
    static bool ValidPath(const std::string &path)
    {
        int count = 0;
        std::vector<std::string> arry;
        Util::Split(path, "/", &arry);
        for (auto &dir : arry)
        {
            if (dir == "..")
            {
                count--;
                if (count < 0)
                {
                    return false;
                }
            }
            else
            {
                count++;
            }
        }
        return true;
    }
};

class HttpRequest
{
public:
    // 请求方法
    std::string _method;
    // 请求uri
    std::string _uri;
    // 请求版本
    std::string _version;
    // 请求正文
    std::string _body;
    // 资源路径的正则提取数据
    std::smatch _matches;
    // 我们的查询字符串
    // GET /search?q=javascript+tutorial&sort=recent&limit=10
    std::unordered_map<std::string, std::string> _params;
    // 头部
    std::unordered_map<std::string, std::string> _headers;

public:
    HttpRequest()
        : _version("HTTP/1.1")
    {
    }
    // 我们每次先获取处理的http上下文，上下文中包含相应 以及应答
    // 每次处理完整的一个请求之后 我们要进行重置上下文 防止对下次请求影响
    void Reset()
    {
        _method.clear();
        _uri.clear();
        _version = "HTTP/1.1";
        _body.clear();
        std::smatch match;
        _matches.swap(match);
        _params.clear();
    }
    // 判断某一个头部字段是否存在
    bool HasHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return false;
        }
        return true;
    }
    std::string GetHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return "";
        }
        return it->second;
    }
    void SetHeaders(const std::string &key, const std::string &val)
    {
        _headers.insert(std::make_pair(key, val));
    }

    // 插入查询字符串
    void SetParam(const std::string &key, const std::string &val)
    {
        _params.insert(std::make_pair(key, val));
    }
    // 判断是否有某个指定的查询字符串
    bool HasParam(const std::string &key) const
    {
        auto it = _params.find(key);
        if (it == _params.end())
        {
            return false;
        }
        return true;
    }
    // 获取指定的查询字符串
    std::string GetParam(const std::string &key) const
    {
        auto it = _params.find(key);
        if (it == _params.end())
        {
            return "";
        }
        return it->second;
    }
    size_t ContentLength() const
    {
        if (HasHeader("Content-Length") == false)
            return 0;
        std::string lenstr = GetHeader("Content-Length");
        return std::stol(lenstr);
    }
    // 判断是长连接还是短连接
    bool Close() const
    {
        // DBG_LOG("HttpRequest,HasHeader(Connection):%d GetHeader(Connection):%s", HasHeader("Connection"), GetHeader("Connection").c_str());

        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
        {
            // 说明是长连接
            return false;
        }
        return true;
    }
};
class HttpResponse
{
    // 设置为共有属性 便于直接赋值
public:
    // 协议版本
    std::string _version;
    // 状态码
    int _status;
    // 头部
    std::unordered_map<std::string, std::string> _headers;
    // 正文
    std::string _body;
    // 重定向标志
    bool _is_redirect;
    // 重定向位置
    std::string _redirecr_uri;

public:
    HttpResponse(int status = 200)
        : _version("HTTP/1.1"),
          _status(status),
          _is_redirect(false)
    {
    }
    void Reset()
    {
        _version = "HTTP/1.1";
        _status = 200;
        _headers.clear();
        _body.clear();
        _is_redirect = false;
        _redirecr_uri.clear();
    }

    // 判断某一个头部字段是否存在
    bool HasHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return false;
        }
        return true;
    }
    std::string GetHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return "";
        }
        return it->second;
    }
    void SetHeaders(const std::string &key, const std::string &val)
    {
        _headers.insert(std::make_pair(key, val));
    }
    // 设置正文的以及正文类型
    void SetBody(const std::string &body, const std::string &type = "text/html")
    {
        _body = body;
        SetHeaders("Content-Type", type);
    }
    // 设置重定向
    void SetRederect(const std::string &rederect, const int status = 302)
    {
        _status = status;
        _is_redirect = true;
        _redirecr_uri = rederect;
    }

    bool Close() const
    {
        // DBG_LOG("HttpRequest,HasHeader(Connection):%d GetHeader(Connection):%s", HasHeader("Connection"), GetHeader("Connection").c_str());

        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
        {
            // 说明是长连接
            return false;
        }
        return true;
    }
};

#define MAX_LINE_LEN 8192
// 解析协议的状态
typedef enum
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
} HttpRecvStatu;
// http协议上下文 记录请求解析到什么哪里了
class HttpContext
{
private:
    int _reps_status; // 解析失败的错误码
    HttpRequest _req;
    HttpRecvStatu _recv_status; // 解析状态
private:
    bool ParseLine(const std::string &line)
    {

        // 进行我们的匹配
        std::regex e("(GET|POST|HEAD|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1.[0|1])(?:\n|\r\n)?", std::regex::icase);
        bool ret = std::regex_match(line, _req._matches, e);
        if (ret == false)
        {
            DBG_LOG("!!! 请求行解析失败 !!!");
            // 提取首行失败
            _recv_status = RECV_HTTP_ERROR;
            _reps_status = 400; // BAD REQUEST
            return false;
        }

        _req._method = _req._matches[1];
        std::transform(_req._method.begin(), _req._method.end(), _req._method.begin(), ::toupper);

        _req._uri = _req._matches[2]; // 我们请求的资源 记得进行解码操作
        Util::UrlDecode(_req._uri, false);

        // 下面就是我们的请求字符串 会有0个或者多个
        std::vector<std::string> arry;
        Util::Split(_req._matches[3], "&", &arry);
        for (auto &ch : arry)
        {
            size_t pos = ch.find('=');
            if (pos == std::string::npos)
            {
                // 没有找到就是坏的查询字符串
                _recv_status = RECV_HTTP_ERROR;
                _reps_status = 400; // BAD REQUEST
                return false;
            }
            std::string key = ch.substr(0, pos);
            std::string val = ch.substr(pos + 1);
            _req.SetParam(Util::UrlDecode(key, true), Util::UrlDecode(val, true));
        }

        // 设置我们的协议版本
        _req._version = _req._matches[4];
        return true;
    }
    bool RecvHttpLine(Buffer *buffer)
    {
        if (_recv_status != RECV_HTTP_LINE)
        {
            return false;
        }

        std::string line = buffer->GetLineAndPop();
        // 数据不够一行
        if (line.size() == 0)
        {

            if (buffer->ReadSpace() >= MAX_LINE_LEN)
            {
                _reps_status = 414;
                _recv_status = RECV_HTTP_ERROR;
                return false;
            }
            // 这里的话可能是因为此时发送的数据 太小不足一行 等待下次 注意这里不算错误
            _recv_status = RECV_HTTP_LINE;
            return true;
        }
        // 此时拿到一行 如果太长了也是错误的
        if (line.size() >= MAX_LINE_LEN)
        {
            _reps_status = 414;
            _recv_status = RECV_HTTP_ERROR;
            return false;
        }
        // 下面就是看一下此时的一行数据 是不是我们的请求行
        bool ret = ParseLine(line);
        if (ret == false)
        {
            return false;
        }

        _recv_status = RECV_HTTP_HEAD;
        return true;
    }
    bool ParseHeadLine(std::string &line)
    {
        // DBG_LOG("\n%s", line.c_str());
        //  注意请求行后面有换行
        if (line.back() == '\n')
        {
            line.pop_back();
        }
        if (line.back() == '\r')
        {
            line.pop_back();
        }
        // Content-Length :
        size_t pos = line.find(": ");
        if (pos == std::string::npos)
        {
            _reps_status = 400;
            _recv_status = RECV_HTTP_ERROR;
            return false;
        }
        std::string key = line.substr(0, pos);
        std::string val = line.substr(pos + 2);
        _req.SetHeaders(key, val);

        return true;
    }
    bool RecvHttpHead(Buffer *buffer)
    {
        if (_recv_status != RECV_HTTP_HEAD)
        {
            return false;
        }
        // 读取多行 知道读取到空行停止
        while (1)
        {
            std::string line = buffer->GetLineAndPop();
            if (line.size() == 0)
            {
                if (buffer->ReadSpace() > MAX_LINE_LEN)
                {
                    _reps_status = 414;
                    _recv_status = RECV_HTTP_ERROR;
                    return false;
                }
            }
            if (line.size() >= MAX_LINE_LEN)
            {
                _reps_status = 414;
                _recv_status = RECV_HTTP_ERROR;
                return false;
            }

            if (line == "\n" || line == "\r\n")
            {
                break;
            }
            bool ret = ParseHeadLine(line);
            if (ret == false)
            {
                return false;
            }
        }
        _recv_status = RECV_HTTP_BODY;
        return true;
    }
    // 注意一个http请求一定是有我们的头部的 但是正文可以没有
    bool RecvHttpBody(Buffer *buffer)
    {
        if (_recv_status != RECV_HTTP_BODY)
        {
            return false;
        }
        // 拿到我们的正文长度
        std::string length = _req.GetHeader("Content-Length");
        // DBG_LOG("string length = _req.GetHeader(Content-length):%s", length.c_str());
        if (length.size() == 0)
        {
            _recv_status = RECV_HTTP_OVER;
            return true;
        }
        // 如果不是我们计算我们要读取的正文长度
        size_t readlength = std::stoi(length) - _req._body.size();
        if (buffer->ReadSpace() < readlength)
        {
            // 有多少拿多少
            _req._body += buffer->ReadAsStringAndPop(buffer->ReadSpace());
            _recv_status = RECV_HTTP_BODY;
            return true;
        }
        // 走到这里我们只读取我们需要的正文 下次请求等下次再来进行读取
        _req._body += buffer->ReadAsStringAndPop(readlength);
        _recv_status = RECV_HTTP_OVER;
        return true;
    }

public:
    HttpContext()
        : _reps_status(200),
          _recv_status(RECV_HTTP_LINE)
    {
    }
    void Reset()
    {
        _reps_status = 200;
        _req.Reset();
        _recv_status = RECV_HTTP_LINE;
    }
    int GetRespStatus()
    {
        return _reps_status;
    }
    HttpRequest GetOneRequest()
    {
        return _req;
    }
    HttpRecvStatu GetRecvStatus()
    {
        return _recv_status;
    }
    void RecvResquest(Buffer *buffer)
    {
        switch (_recv_status)
        {
        case RECV_HTTP_LINE:
            RecvHttpLine(buffer);

        case RECV_HTTP_HEAD:
            RecvHttpHead(buffer);

        case RECV_HTTP_BODY:
            RecvHttpBody(buffer);
        }
    }
};

class HttpServe
{
private:
    using Handler = std::function<void(const HttpRequest &, HttpResponse *)>;
    using Handlers = std::vector<std::pair<std::regex, Handler>>; // 这里用正则表达式 是为了匹配 /login/123 /login/4324 这种功能性请求
    // 四种我们的路由表 都是查找我们功能请求的
    Handlers _get_route;
    Handlers _post_route;
    Handlers _delete_route;
    Handlers _put_route;
    std::string _basedir;
    TcpServe _serve;

private:
    void OnConneted(const PtrConnection &conn)
    {

        conn->SetContext(HttpContext());
    }
    void OnMessage(const PtrConnection &conn, Buffer *buffer)
    {

        while (buffer->ReadSpace() > 0)
        {
            // 获取上下文
            HttpContext *context = conn->Context()->GetVal<HttpContext>();

            // 我们读取一个请求
            // DBG_LOG(" HttpContext context%s")
            context->RecvResquest(buffer);
            // 拿到我们此时的请求
            HttpRequest request = context->GetOneRequest();

            if (context->GetRecvStatus() == RECV_HTTP_OVER)
            {
            }
            else if (context->GetRecvStatus() == RECV_HTTP_ERROR)
            {
            }
            HttpResponse resp(context->GetRespStatus());
            if (context->GetRespStatus() >= 400)
            {
                // 获取一个完整的请求失败了
                ErrorHandler(request, &resp);
                // DBG_LOG("request body:\n%s", request._body.c_str());
                SendResponse(conn, request, resp);
                // 直接关闭连接 以及进行缓冲区清空
                // 清空上下文
                context->Reset();
                buffer->MoveReadInd(buffer->ReadSpace());
                conn->ShutDown();
                return;
            }
            if (context->GetRecvStatus() != RECV_HTTP_OVER)
            {
                DBG_LOG("recv_status:%d", context->GetRecvStatus());

                return;
            }

            Route(request, &resp);

            SendResponse(conn, request, resp);
            context->Reset();

            if (resp.Close() == true)
                conn->ShutDown();
        }
    }
    void OnClose(const PtrConnection &conn)
    {
        // DBG_LOG("connection release:%p", conn.get());
    }
    bool IsStaticResourceRequest(const HttpRequest &req, std::string &path)
    {
        // 判断是否设置了我们的资源路径
        if (_basedir.empty() == true)
            return false;
        if (req._method != "GET" && req._method != "HEAD")
            return false;
        // 判断路径是否合法
        if (Util::ValidPath(req._uri) == false)
            return false;

        // 判断一下请求的是不是普通文件
        // 注意如果此时uri 就是一个/目录 我们加上我们返回首页
        if (req._uri == "/" || req._uri.size() == 0)
        {
            path = _basedir + "/index.html";
        }
        else
        {
            path = _basedir + req._uri;
        }
        // 下面判断是不是我们的普通文件
        if (Util::IsRegular(path) == false)
            return false;
        return true;
    }

    void HandlerStaticResource(const HttpRequest &request, HttpResponse *resp, std::string &path)
    {
        // DBG_LOG("Statuc Souerce,path:%s", path.c_str());
        std::string tem;
        bool ret = Util::ReadFile(path, &tem);
        // DBG_LOG("send mess:%s", tem.c_str());
        if (ret == false)
        {
            return;
        }
        std::string mine = Util::ExtMime(path);
        resp->SetBody(tem, mine);
        // 其实这里不设置也可以 因为发送的时候会进行我们的正文判断 发现没有对应的长度 或者正文类型
        // 发送的时候会进行补充
        resp->SetHeaders("Content-Length", std::to_string(resp->_body.size()));
        resp->SetHeaders("Content-Type", mine);
        return;
    }
    void Dispatcher(const HttpRequest &request, HttpResponse *response, Handlers &route)
    {
        std::string url = request._uri;
        // 下面遍历所有的表项 去每一个表项的第一个数据 就是正则表达式 与我们的功能请求的url进行匹配
        for (auto &ch : route)
        {
            std::smatch matchs;
            std::regex e = ch.first;
            if (std::regex_match(url, matchs, e) == true)
            {

                ch.second(request, response);

                return;
            }
        }

        response->_status = 404;
    }
    void Route(const HttpRequest &request, HttpResponse *resp)
    {
        // DBG_LOG("Route");
        //  先进行静态资源请求 如果没有就是功能性请求

        std::string path;
        if (IsStaticResourceRequest(request, path))
        {

            HandlerStaticResource(request, resp, path);
            return;
        }

        // 下面就是功能性请求 去查找我们的路由表
        if (request._method == "GET" || request._method == "HEAD")
        {

            return Dispatcher(request, resp, _get_route);
        }
        else if (request._method == "POST")
        {

            return Dispatcher(request, resp, _post_route);
        }
        else if (request._method == "PUT")
        {

            // DBG_LOG("进入put");
            return Dispatcher(request, resp, _put_route);
        }
        else if (request._method == "DELETE")
        {

            return Dispatcher(request, resp, _delete_route);
        }

        resp->_status = 405;
        return;
    }

    void ErrorHandler(const HttpRequest &request, HttpResponse *resp)
    {
        // 1. 组织一个错误展示页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(resp->_status);
        body += " ";
        body += Util::StatuDesc(resp->_status);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        // 2. 将页面数据，当作响应正文，放入rsp中
        resp->SetBody(body, "text/html");
    }

    void SendResponse(const PtrConnection &conn, const HttpRequest &request, HttpResponse &resp)
    {
        DBG_LOG("发送响应，请求版本: %s", request._version.c_str());

        // DBG_LOG("request conection:%s", request.GetHeader("Connection").c_str());
        if (request.Close() == true)
        {
            resp.SetHeaders("Connection", "close");
        }
        else
        {
            resp.SetHeaders("Connection", "keep-alive");
        }
        // 经过业务处理 把正文填好 我们在发送的时候进行头部字段的补充
        if (resp._body.empty() == false && resp.HasHeader("Content-Length") == false)
        {
            resp.SetHeaders("Content-Length", std::to_string(resp._body.size()));
        }
        if (resp._body.empty() == false && resp.HasHeader("Content-Type") == false)
        {
            resp.SetHeaders("Content-Type", "application/octet-stream");
        }
        if (resp._is_redirect == true)
        {
            resp.SetHeaders("Location", resp._redirecr_uri);
        }

        // 下面进行
        std::stringstream ss;
        ss << request._version << " " << resp._status << " " << Util::StatuDesc(resp._status) << "\r\n";
        for (auto &ch : resp._headers)
        {
            ss << ch.first << ": " << ch.second << "\r\n";
        }
        ss << "\r\n";
        // DBG_LOG("ResPonse Head:\n%s", ss.str().c_str());
        ss << resp._body;
        conn->Send(ss.str().c_str(), ss.str().size());
    }

public:
    HttpServe(int port, int timeout = 30)
        : _serve(port)
    {
        _serve.EnableInactiveRelase(timeout);
        _serve.SetMessageCallback(std::bind(&HttpServe::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
        _serve.SetConnectedCallback(std::bind(&HttpServe::OnConneted, this, std::placeholders::_1));
        _serve.SetClosedCallback(std::bind(&HttpServe::OnClose, this, std::placeholders::_1));
        // 其实就是这里没有问题 这里我们没有给我们的服务器实现任意事件回调 这取决了用户使用者
        // 但是我们的超时连接 在我们分配连接的时候就在连接模块 内部自己设置了任意事件的回调就是刷新活跃度
    }
    void SetThreadCount(int count)
    {
        _serve.SetThreadCount(count);
    }
    void SeTBaseDir(const std::string filename)
    {
        assert(Util::IsDirectory(filename) == true);
        _basedir = filename;
    }

    void Start()
    {
        _serve.Start();
    }

    void AddGetHandler(const std::string &FunctionRequest, const Handler &method)
    {
        _get_route.push_back(std::make_pair(std::regex(FunctionRequest), method));
    }
    void AddPostHandler(const std::string &FunctionRequest, const Handler &method)
    {
        _post_route.push_back(std::make_pair(std::regex(FunctionRequest), method));
    }
    void AddDeleteHandler(const std::string &FunctionRequest, const Handler &method)
    {
        _delete_route.push_back(std::make_pair(std::regex(FunctionRequest), method));
    }
    void AddPutHandler(const std::string &FunctionRequest, const Handler &method)
    {
        _put_route.push_back(std::make_pair(std::regex(FunctionRequest), method));
    }
};
